package com.lzy.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.common.QueryPageParam;
import com.lzy.entity.Class;
import com.lzy.entity.Result;
import com.lzy.service.IClassService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-04-26
 */
@RestController
@RequestMapping("/class")
public class ClassController {

    private static final Logger log = LoggerFactory.getLogger(ClassController.class);

    @Autowired
    private IClassService classService;

    //分页查询班级信息
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        log.info("分页查询参数：{}", query);
        Page<Class> page = new Page<>(query.getPageNum(), query.getPageSize());
        IPage result = classService.getPage(page, query.getParam());
        return Result.success(result.getRecords(), result.getTotal());
    }

    //获取所有班级列表
    @GetMapping("/list")
    public Result list() {
        log.info("获取所有班级列表");
        List<Class> list = classService.list();
        return Result.success(list);
    }

    //新增班级信息
    @PostMapping("/create")
    public Result create(@RequestBody Class classInfo) {
        log.info("新增班级信息：{}", classInfo);
        return classService.addClass(classInfo);
    }

    //修改班级信息
    @PostMapping("/update")
    public Result update(@RequestBody Class classInfo) {
        log.info("修改班级信息：{}", classInfo);
        return classService.updateById(classInfo) ? Result.success() : Result.fail();
    }

    //删除班级信息
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        log.info("删除班级信息：{}", id);
        return classService.removeById(id) ? Result.success() : Result.fail();
    }

    /**
     * 班级名称唯一性校验
     * @param className
     */
    @GetMapping("/checkClassName")
    public Result checkClassName(@RequestParam String className) {
        log.info("班级名称唯一性校验：{}", className);
        LambdaQueryWrapper<Class> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Class::getClassName, className);
        Class one = classService.getOne(queryWrapper);
        return one == null ? Result.success() : Result.success("该班级名称已经存在,请更换班级名称");
    }

}
